package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ResponseEnum;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author pandengzhu
 * @since 2024-03-19
 */
@Api(tags = "小结管理")
//@CrossOrigin
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {

    @Resource
    private EduVideoService eduVideoService;

    @Resource
    private VodClient vodClient;


    /**
     * addVideo
     *
     * @param eduVideo
     * @return
     */
    @ApiOperation("添加小结")
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok().message("添加小结成功");
    }

    /**
     * 删除小节，删除对应阿里云视频
     *
     * @param id
     * @return
     */
    @ApiOperation("删除小结")
    @DeleteMapping("/delete/{id}")
    public R removeById(@PathVariable String id) {

        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if (StringUtils.isNotBlank(videoSourceId)) {

            //根据视频id，远程调用实现视频删除
            R result = vodClient.removeVideo(videoSourceId);
            if (result.getCode() == -109) {
                throw new BusinessException(ResponseEnum.DELETE_BATCH_VIDEO_ERROR.getCode(),ResponseEnum.DELETE_BATCH_VIDEO_ERROR.getMessage());
            }

        }

        //删除小结
        eduVideoService.removeById(id);
        return R.ok().message("删除小结成功");
    }

    /**
     * 修改小结
     *
     * @param eduVideo
     * @return
     */
    @ApiOperation("修改小结")
    @PostMapping("/update")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    /**
     * 根据小结id查询
     *
     * @param id
     * @return
     */
    @ApiOperation("根据小结id查询")
    @GetMapping("/select/{id}")
    public R getVideo(@PathVariable String id) {
        EduVideo eduVideo = eduVideoService.getById(id);
        return R.ok().data("eduVideo", eduVideo);
    }

}

